package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CorsFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        Filter.super.init(config);
    }

    public void destroy() {
        Filter.super.destroy();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        //设置允许跨域请求的请求头
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        //请求的有效时间，单位为秒
        httpResponse.setHeader("Access-Control-Max-Age", "3600");
        // 设置允许的Header
        httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, content-type");
        //过滤器链继续执行
        chain.doFilter(request, response);
    }
}
